/*******************************************************************************
 * Software Name : Android Simple Downloader
 *
 * Copyright © 2012 Rinvay Tang
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package com.rinvay.network.filedownload.model;

public class Part 
{

	private DownloadTask resource = null;
	private int begin;
	/**
	 * 分块的大小<br>
	 * 如果资源大小未知的话，只分成一块，且size为－1
	 */
	private int size;
	private int curLength;
	private int state;
	
	private boolean lock = false;
	
	private int attempts = 0;
	
	private static final int MAX_ATTEMPTS = 3;

	/**
	 * 构建Part，来自新建任务和任务记录
	 * @param resource 归属的下载任务
	 * @param begin Part开始字节
	 * @param size Part的大小
	 * @param curLength Part已下载的进度
	 */
	public Part(DownloadTask resource, int begin, int size, int curLength) {
		this.resource = resource;
		this.begin = begin;
		this.size = size;
		this.curLength = curLength;
	}
	
	public boolean isPartFinished() {
		return curLength >= size;
	}

	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Part[")
		       .append("size:" + size + "|")
			   .append("(" + begin + "-" + (begin + size - 1) + ")")
			   .append("]");
		return builder.toString();
	}

	public DownloadTask getResource() {
		return resource;
	}

	public int getBegin() {
		return begin;
	}

	public int getSize() {
		return size;
	}

	public int getCurLength() {
		return curLength;
	}

	public void setCurLength(int curLength) {
		this.curLength = curLength;
	}

	public int getState() {
		return state;
	}

	public void setState(int state) {
		this.state = state;
		resource.setState(state);
	}

	public boolean isLock() {
		return lock;
	}

	public void setLock(boolean lock) {
		this.lock = lock;
	}

	public boolean isOverAttempts() {
		return (attempts >= MAX_ATTEMPTS);
	}

	public void increaseAttempts() {
		this.attempts++;
	}
	
	

}
